package service;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import model.Cliente;
import model.Venda;
import model.Vendedor;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.ejb.EntityManagerImpl;

import util.DataUtil;

public class VendaService {
	
	protected EntityManager entityManager;
	
	public VendaService(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public Venda criaVenda(Cliente cliente, 
			Long valorTotal, Vendedor vendedor, long data) {
		Venda venda = new Venda();
		venda.setCliente(cliente);
		venda.setValorTotal(valorTotal);
		venda.setVendedor(vendedor);
		venda.setDataVenda(DataUtil.criaData(data));
		
		insereVenda(venda);
		return venda;
	}
	
	public Venda findVenda(Long id) {
		Venda Venda = entityManager.getReference(Venda.class, id);
		return Venda;
	}
	
	public List<Venda> listaVendas() {
		TypedQuery<Venda> query = entityManager.createQuery(
				"SELECT e FROM Venda e", Venda.class);
		return query.getResultList();
	}
	
	public void deletaVendas() {
		TypedQuery<Venda> query = entityManager.createQuery(
				"DELETE FROM Venda", Venda.class);
		query.executeUpdate();
	}
	
	public void insereVenda(Venda emp) {
		entityManager.persist(emp);
	}
	
	public List<Venda> getTotalVendasPorVendedor(Long vendedorId) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(Venda.class);
		criteria.add(Restrictions.eq("vendedor.codigo", vendedorId));
		
		@SuppressWarnings("unchecked")
		List<Venda> results = criteria.list();
		
		return results;
		
	}
	
	
	public List<Venda> getTotalVendas(Long dataVenda) {
		Session session = getSession();
		Criteria criteria = session.createCriteria(Venda.class);
		Date data = DataUtil.criaData(dataVenda);
		criteria.add(Restrictions.eq("dataVenda", data));
		
		@SuppressWarnings("unchecked")
		List<Venda> results = criteria.list();
		
		return results;
		
	}
	
	private Session getSession() {
		Session session;
		if (entityManager.getDelegate() instanceof EntityManagerImpl) {
			EntityManagerImpl entityManagerImpl = (EntityManagerImpl) entityManager
					.getDelegate();
			session = entityManagerImpl.getSession();
		} else {
			session = (Session) entityManager.getDelegate();
		}
		return session;
	}
	
	public void removeVenda(Long id) {
		Venda venda = findVenda(id);
		if (venda != null) {
			entityManager.remove(venda);
		}
	}
}
